package com.project.nimsen.web.sys;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.project.nimsen.common.FileUpload;
import com.project.nimsen.common.impl.FileUploadWebInsert;
import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.constant.ModelConstant;
import com.project.nimsen.dto.ModelDto;
import com.project.nimsen.entity.Modelinfo;
import com.project.nimsen.entity.User;
import com.project.nimsen.service.IModelinfoService;
import com.project.nimsen.util.WebUtil;
import com.project.nimsen.util.ZipUtilsTool;
import com.project.jdbc.utils.DateUtils;
import com.project.jdbc.utils.Page;
import com.project.jdbc.web.BaseMVCAction;
/**
 * 模版Control
 * */
@Controller
@RequestMapping(value ="/sys/model")
public class ModelControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IModelinfoService modelService;
	@RequestMapping(value ="/list")
	public String list(){
		return "/WEB-INF/sys/model/list";
	}
	/**
	 * 查询方法
	 * */
	@RequestMapping(value = "/search")
	@ResponseBody
	public Map<String, Object> search(HttpServletRequest request,HttpServletResponse response){
		//分页信息
		Page page = new Page(getIntegerParameter("page"));
		page.setPageSize(getIntegerParameter("rows"));
		//返回JSON信息
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", 0);
		//查询条件设置
		ModelDto dto = new ModelDto();
		dto.setPage(page);
		String type = getParameter("model");
		if(StringUtils.isNotBlank(type)){
			if(ModelConstant.PAD.equals(type))
				dto.setModel(ModelConstant.PAD);
			else if(ModelConstant.PHONE.equals(type))
				dto.setModel(ModelConstant.PHONE);
			else
				dto.setModel(ModelConstant.PC);
		}
		
		//查询信息
		try {
			List<Map<String, Object>> rows = modelService.finder(dto);
			if(CollectionUtils.isEmpty(rows)){
				map.put("rows", "");
				return map;
			}
			//转换时间
			for(Map<String, Object> row : rows){
				Date createTime = (Date)row.get("createTime");
				row.put("createTime", DateUtils.convertDate2String(createTime));
				String model = row.get("model").toString();
				if(ModelConstant.PAD.equals(model))
					row.put("model", "平板模版");
				else if(ModelConstant.PHONE.equals(model))
					row.put("model", "手机模版");
				else
					row.put("model", "电脑模版");
			}
			map.put("rows", rows);
			map.put("total", page.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	
	@RequestMapping(value="/validate")
	@ResponseBody
	public Map<String,Object> validate(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			//查询条件设置
			ModelDto dto = new ModelDto();
			dto.setId(getParameter("id"));
			dto.setValifield("modelname");
			dto.setValivalue(getParameter("modelname"));
			
			Map<String, Object> model = modelService.findVilidate(dto);
			if(model!=null){
				map.put("success", false);
				map.put("message", "系统中已经存在名为"+dto.getModelname()+"的模版!");
			}else{
				map.put("success", true);
				map.put("message", "");
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	@RequestMapping(value="/add")
	public void add(HttpServletRequest request,	@RequestParam(value="modelfile") MultipartFile uploadFile,
		@RequestParam(value="model")String modelStr,HttpServletResponse response,@RequestParam(value="modeldesc")
		String modeldesc,@RequestParam(value="id") String id){
		User curUser = webUtil.getCurrUser();
		try {
			String autoName = "";
			//保存数据
			Modelinfo model = null;
			if(StringUtils.isBlank(id)){
				model = new Modelinfo();
				model.setActive(0);
				model.setCreateTime(new Date());
				model.setCreateUser(curUser.getId());
			}else{
				model = modelService.findEntityById(id);
				autoName = model.getModelname();
			}
			if(uploadFile.getSize()>0){
				//上传文件
				String srcname = new String(uploadFile.getOriginalFilename().getBytes("ISO8859-1"),"UTF-8");
				FileUpload upload = new FileUploadWebInsert(uploadFile.getBytes(), srcname, request, NimsenConstant.THEMES_PATH);
				upload.upload();
				//自动生成的文件名称
				autoName = upload.getAutoFilename();
				
				//解压上传的模版
				ServletContext sevcon = request.getSession().getServletContext();
				String allPath = sevcon.getRealPath(File.separator+NimsenConstant.THEMES_PATH);
				File unzipFile = new File(allPath+File.separator+autoName);
				ZipUtilsTool.unzip(unzipFile, allPath);
				unzipFile.delete();
				//判断是否为修改后又上传的模版
				if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(model.getModelname())){
					//FileUtil.DeleteDirectory(allPath+File.separator+model.getModelname());
				}
			}
			
			
			if(ModelConstant.PAD.equals(modelStr))
				model.setModel(ModelConstant.PAD);
			else if(ModelConstant.PHONE.equals(modelStr))
				model.setModel(ModelConstant.PHONE);
			else
				model.setModel(ModelConstant.PC);
			model.setModeldesc(modeldesc);
			if(autoName.lastIndexOf(".")>0)
				model.setModelname(autoName.substring(0, autoName.lastIndexOf(".")));
			else
				model.setModelname(autoName);
			//保存或者修改信息
			if(StringUtils.isNotBlank(id))
				modelService.update(model);
			else
				modelService.save(model);
			response.getWriter().println(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}
	/**
	 * 删除一个用户
	 * */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String id = getParameter("id");
		try {
			if(modelService.deleteById(id)){
				map.put("success", false);
				map.put("message", "删除失败，还有用此模板的用户。");
			}
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 向前台返回一个实体
	 * */
	@RequestMapping(value = "/bean")
	@ResponseBody
	public Map<String, Object> bean(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String id = getParameter("id");
		try {
			Map<String, Object> entity = modelService.findByid(id);
			if(entity==null){
				map.put("success", false);
				map.put("message", "没有要修改的模版！");
				return map;
			}
			map.put("success", true);
			map.put("bean", entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			map.put("success", false);
		}
		return map;
	}
	/**
	 * 模版浏览
	 * */
	@RequestMapping(value = "/themes")
	@ResponseBody
	public Map<String, Object> themes(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String,Object>();
		ServletContext sevcon = request.getSession().getServletContext();
		String path = getParameter("path");
		String id = getParameter("id");
		try {
			//判断路径是否为空
			if(StringUtils.isBlank(path)){
				if(StringUtils.isBlank(id)){
					map.put("total", 0);
					return map;
				}else{
					Modelinfo model = modelService.findEntityById(id);
					if(model==null){
						map.put("total", 0);
						return map;
					}
					path = model.getModelname();
				}
			}
			File dirThemes = new File(sevcon.getRealPath("themes")+File.separator+path);
			File [] files = dirThemes.listFiles();
			int fileCount = files.length;
			map.put("total", fileCount);
			List<Map<String,Object>> rows = new ArrayList<Map<String, Object>>();
			for(int i=0;i<fileCount;i++){
				Map<String, Object> row = new HashMap<String, Object>();
				File file = files[i];
				if(file.isDirectory())
					continue;
				String fileName = file.getName();
				//如果文件没有扩展名处理
				if(!(fileName.lastIndexOf(".")>0))
					continue;
				//只处理html的文件
				if(!".html".equals(fileName.substring(fileName.lastIndexOf("."))))
					continue;
				row.put("filename", fileName);
				
				rows.add(row);
			}
			map.put("rows", rows);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
}
